from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from .models import Order, OrderItem, RefundRequest, ShippingAddress
from .serializers import (
    OrderListSerializer, OrderDetailSerializer, OrderCreateSerializer,
    RefundRequestSerializer, RefundRequestAdminSerializer,
    ShippingAddressSerializer
)
from .filters import OrderFilter


class OrderListView(generics.ListAPIView):
    serializer_class = OrderListSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = OrderFilter
    ordering_fields = ['created_at', 'total_amount', 'status']
    ordering = ['-created_at']
    
    def get_queryset(self):
        return Order.objects.filter(user=self.request.user)


class OrderDetailView(generics.RetrieveAPIView):
    serializer_class = OrderDetailSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Order.objects.filter(user=self.request.user)


class OrderCreateView(generics.CreateAPIView):
    serializer_class = OrderCreateSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        order = serializer.save()
        
        return Response(
            OrderDetailSerializer(order).data,
            status=status.HTTP_201_CREATED
        )


class OrderCancelView(generics.UpdateAPIView):
    serializer_class = OrderDetailSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return Order.objects.filter(user=self.request.user)
    
    def patch(self, request, *args, **kwargs):
        order = self.get_object()
        
        if order.status not in ['pending', 'confirmed']:
            return Response(
                {'error': '当前订单状态无法取消'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        order.status = 'cancelled'
        order.save()
        
        # 恢复库存
        for item in order.items.all():
            book = item.book
            book.stock_quantity += item.quantity
            book.save()
        
        return Response({
            'message': '订单已取消',
            'order': OrderDetailSerializer(order).data
        })


class OrderAdminListView(generics.ListAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderDetailSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = OrderFilter
    ordering_fields = ['created_at', 'total_amount', 'status']
    ordering = ['-created_at']


class OrderAdminUpdateView(generics.UpdateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderDetailSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def patch(self, request, *args, **kwargs):
        order = self.get_object()
        old_status = order.status
        
        serializer = self.get_serializer(order, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        
        # 如果状态发生变化，记录状态历史
        if old_status != order.status:
            order.status_history.create(
                status=order.status,
                note=f"管理员 {request.user.email} 更新订单状态"
            )
        
        return Response(serializer.data)


class ShippingAddressListView(generics.ListCreateAPIView):
    serializer_class = ShippingAddressSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return ShippingAddress.objects.filter(user=self.request.user)
    
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class ShippingAddressDetailView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ShippingAddressSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return ShippingAddress.objects.filter(user=self.request.user)


class RefundRequestListView(generics.ListCreateAPIView):
    serializer_class = RefundRequestSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return RefundRequest.objects.filter(user=self.request.user)
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 验证订单是否属于当前用户
        order = serializer.validated_data['order']
        if order.user != request.user:
            return Response(
                {'error': '无权申请该订单的退款'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 验证订单状态
        if order.status not in ['delivered', 'completed']:
            return Response(
                {'error': '订单状态不符合退款条件'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 验证是否已有退款申请
        if RefundRequest.objects.filter(order=order, user=request.user).exists():
            return Response(
                {'error': '该订单已有退款申请'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        refund_request = serializer.save()
        return Response(
            RefundRequestSerializer(refund_request).data,
            status=status.HTTP_201_CREATED
        )


class RefundRequestAdminListView(generics.ListAPIView):
    queryset = RefundRequest.objects.all()
    serializer_class = RefundRequestAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    ordering_fields = ['created_at', 'status']
    ordering = ['-created_at']


class RefundRequestAdminUpdateView(generics.UpdateAPIView):
    queryset = RefundRequest.objects.all()
    serializer_class = RefundRequestAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def patch(self, request, *args, **kwargs):
        refund_request = self.get_object()
        old_status = refund_request.status
        
        serializer = self.get_serializer(
            refund_request, 
            data=request.data, 
            partial=True
        )
        serializer.is_valid(raise_exception=True)
        serializer.save(processed_by=request.user)
        
        # 如果退款被批准，更新订单状态
        if old_status != 'approved' and refund_request.status == 'approved':
            order = refund_request.order
            order.status = 'refunded'
            order.save()
        
        return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def order_stats(request):
    user = request.user
    orders = Order.objects.filter(user=user)
    
    stats = {
        'total_orders': orders.count(),
        'pending_orders': orders.filter(status='pending').count(),
        'completed_orders': orders.filter(status='completed').count(),
        'cancelled_orders': orders.filter(status='cancelled').count(),
        'total_spent': sum(order.final_amount for order in orders.filter(status__in=['completed', 'delivered'])),
    }
    
    return Response(stats)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def admin_order_stats(request):
    from django.db.models import Sum, Count, Avg
    
    orders = Order.objects.all()
    
    stats = {
        'total_orders': orders.count(),
        'today_orders': orders.filter(created_at__date=timezone.now().date()).count(),
        'pending_orders': orders.filter(status='pending').count(),
        'processing_orders': orders.filter(status='processing').count(),
        'shipped_orders': orders.filter(status='shipped').count(),
        'delivered_orders': orders.filter(status='delivered').count(),
        'total_revenue': orders.filter(status__in=['completed', 'delivered']).aggregate(
            total=Sum('final_amount')
        )['total'] or 0,
        'average_order_value': orders.filter(status__in=['completed', 'delivered']).aggregate(
            avg=Avg('final_amount')
        )['avg'] or 0,
    }
    
    return Response(stats)
